package com.lincoln.Client.context;

import com.lincoln.Client.Robot.ThreadRobot;
import com.lincoln.wechat.WeChatBot;
import com.lincoln.wechat.api.annotation.Bind;
import com.lincoln.wechat.api.constant.Config;
import com.lincoln.wechat.api.model.WeChatMessage;
import com.lincoln.wechat.exception.WeChatException;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//机器人上下文
public class RobotContext {
    public static Map<String, ThreadRobot> bots = new ConcurrentHashMap<>();
    public static String newestRobotKey = "";
    public static String groupId = "";

    /**
     * 新增一个机器人实例,返回机器人key
     *
     * @return
     */
    public static String addBot() {
        String key = getNewKey();
        ThreadRobot robot = new ThreadRobot(key, Config.me().autoLogin(false).showTerminal(true));
        newestRobotKey = key;
        //将消息绑定事件加入WeChatBot
        robot.loadBind(MessageFactory.class);
        bots.put(key, robot);
        return key;
    }

    /**
     * 通过key取到机器人
     *
     * @param key
     * @return
     */
    public static ThreadRobot getRobot(String key) {
        return bots.get(key);
    }

    public static ThreadRobot getNewestRobot() {
        return bots.get(newestRobotKey);
    }

    /**
     * 通过key删除机器人
     *
     * @param key
     */
    public static void removeRobot(String key) {
        bots.remove(key);
        if (FrameContext.accountManage != null) {
            FrameContext.accountManage.flashFrame();
        }
    }

    /**
     * 新增机器人实例时生成一个唯一的key标识机器人
     *
     * @return
     */
    private static String getNewKey() {
        return String.valueOf(new Date().getTime());
    }

    /**
     * 发送消息
     *
     * @param msg
     */
    public static void sendMsg(String msg) {
        sendMsgTest(msg);
        try {
            getNewestRobot().api().sendText(groupId, msg);
        }catch (Exception e){
            System.out.println("没开微信");
        }
    }

    public static void sendMsgTest(String msg) {
        String toUser = "";
        System.out.println(msg);
    }
}
